package cn.xiaoyu.su.component;

import cn.xiaoyu.su.util.CommonUtil;
import org.springframework.stereotype.Component;

/**
 * @author sufs
 * @date 2022/11/1 18:09
 */
@Component
public class ShortLinkComponent {

    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 创建短链
     * @param originalUrl
     * @return db编码+6位短链编码
     */
    public String createShortLinkCode(String originalUrl) {
        long murmur32 = CommonUtil.murmurHash32(originalUrl);
        //转62进制
        String shortLinkCode = encodeToBase62(murmur32);
        return shortLinkCode;
    }



    /**
     * 10进制转62进制
     * @param num
     * @return
     */
    private static String encodeToBase62(long num) {
        //StringBuffer：线程安全; StringBuilder：线程不安全
        StringBuffer sb = new StringBuffer();
        do {
            int i = (int) (num % 62);
            sb.append(CHARS.charAt(i));
            num /= 62;
            // num = num/ 62;
        } while (num > 0);
        String value = sb.reverse().toString();
        return value;
    }
}
